package com.mate.cloud.redisson.scheduler;

import com.mate.cloud.redisson.service.TagService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * Java 应用内定时任务（Spring Boot）
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/8/19 10:43
 * @updateUser:     MI
 * @updateTime:     2025/8/19 10:43
 * @updateRemark:   修改内容
 * @version:        1.0
 */
@Slf4j
@Component
public class TagCleanupScheduler {


    @Resource
    private TagService tagService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 每天凌晨3点执行
    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanupUnusedTags() {
        String luaScript = "local sixMonthsAgo = tonumber(redis.call('TIME')[1]) - 15552000 " +
                "local unusedTags = redis.call('ZRANGEBYSCORE', 'tag:last_used', '-inf', sixMonthsAgo) " +
                "for _, tag in ipairs(unusedTags) do " +
                "    redis.call('DEL', 'tag:'..tag) " +
                "    redis.call('DEL', 'tag:metadata:'..tag) " +
                "    redis.call('ZREM', 'tag:hot', tag) " +
                "    redis.call('ZREM', 'tag:last_used', tag) " +
                "    redis.call('DEL', 'tag:autocomplete:'..tag) " +
                "end " +
                "return #unusedTags";

        Long cleanedCount = stringRedisTemplate.execute(
                new RedisCallback<Long>() {
                    @Override
                    public Long doInRedis(RedisConnection connection) {
                        return connection.eval(
                                luaScript.getBytes(),
                                ReturnType.INTEGER,
                                0,
                                new byte[0][]
                        );
                    }
                }
        );

        log.info("清理了 {} 个未使用标签", cleanedCount);
    }
    // 每天凌晨4点
    @Scheduled(cron = "0 0 4 * * ?")
    public void dailyCleanup() {
        int cleaned = tagService.cleanupUnusedTags(6);
    }
}
